let { User, Message, Comment, question } = require("../models");
const { username } = require("../db/config");
let auto = require("../utils/auth")

let index_fn = async (ctx, next) => {
    let username = ctx.session.userName;
    let userIds = [];
    // 所有的说说
    let msgs = JSON.parse(JSON.stringify(await Message.findAll({
        order: [
            ['id', 'desc']
        ]
    })));
    let msgIds = [];
    //把查出来的的id存入数据
    msgs.forEach(item => {
        msgIds.push(item.id);
        userIds.push(item.fromUserId);
    });
    //push() 方法可向数组的末尾添加一个或多个元素，并返回新的长度。

    // 所有的吐槽（如果有分页，可以根据查出来的说说的id，来查询所对应的所有的吐槽）
    let comments = JSON.parse(JSON.stringify(await Comment.findAll({
        where: {
            msgId: msgIds
        }
    })));

    comments.forEach(item => {
        userIds.push(item.fromUserId);
    });

    let userAll = await User.findAll({
        where: {
            id: userIds
        }
    });

    // 遍历所有的评论，给每一个评论的fromUserId加上用户名称
    comments.forEach(item => {
        let userInfo = userAll.filter(row => {
            return item.fromUserId === row.id;
        })[0];
        item.comUserName = userInfo === undefined ? '匿名' : userInfo.username;
    })

    // 组合成上下级关系
    msgs.forEach(msg => {
        let sayComments = comments.filter(item => {
            return item.msgId === msg.id;
        });
        let userInfo = userAll.filter(row => {
            return msg.fromUserId === row.id;
        })[0];
        msg.msgUserName = userInfo === undefined ? '匿名' : userInfo.username;
        msg.comments = sayComments;
    })


    let obj = {
        username,
        msgs
    };
    ctx.render('index.html', obj);
};



let login_fn = async (ctx, next) => {
    ctx.render('login.html');
};
let register_fn = async (ctx, next) => {
    ctx.render('register.html', { msg: '' });
};

let loginDone_fn = async (ctx, next) => {
    let username = ctx.request.body.Username || '';
    let password = ctx.request.body.Password || '';

    console.log(username);
    console.log(password);
    let res;
    //查找条件有用户名username和密码passw的所有库里的表
    let u1 = await User.findOne({
        where: {
            username: username,
            password: password
        }
    });
    let user = JSON.stringify(u1);//JSON.stringify() 方法用于将 JavaScript 值转换为 JSON 字符串。
    let u2 = JSON.parse(user);//JSON 通常用于与服务端交换数据。服务器接收数据
    console.log(user);
    console.log(u2);
    //如果找到代表登入成功传回状态码提升登入成功
    if (user !== 'null') {
        ctx.session.userId = u2.id;
        ctx.session.userName = u2.username;
        res = { code: 200, msg: '登录成功' };
    } else {
        res = { code: 1000, msg: '用户名或密码错误，请重试' };
    }

    ctx.body = JSON.stringify(res);
};

let registerDone_fn = async (ctx, next) => {
    let uid = ctx.request.body.username || '';
    let pwd = ctx.request.body.password || '';
    let confirmpassword = ctx.request.body.confirmpassword || '';
    let res = ""
    console.log(uid);
    //条件验证
    // 判断用户名、密码是否为空，为空则返回提示信息；不为空则尝试从数据库中查询是否有同名用户，如果没有，则创建用户；如果有，则返回提示信息；
    // 初步尝试then的玩法，出现了一些顺序问题（前端获取的返回数据为空的情况）
    if (uid.length > 0 && pwd.length > 0 && confirmpassword.length > 0 && pwd === confirmpassword) {
        //查找库里有没有这个用户
        let userDNA = await User.findOne({ where: { username: uid } })
        let ui1 = JSON.stringify(userDNA)

        console.log(ui1);
        if (ui1 === "null") {
            console.log("没有用户");
            let u2 = await User.create
                ({
                    username: uid,
                    password: pwd
                })
            let uijosn = JSON.stringify(u2)
            if (uijosn !== "null") {
                res = { code: 200, msg: "注册成功" }
            } else { res = { code, msg: "注册失败" } }

        } else {
            res = { code: 1000, msg: "当前用户已经存在请重新开始" }
        }

    } else { res = { code: 1000, msg: "用户名密码不能为空" } }
    ctx.body = JSON.stringify(res);
};//注销
let logout_fn = async (ctx, next) => {
    ctx.session = null;
    ctx.body = { code: 200, msg: '注销成功' };
}
// 说说调用的方法
let say_fn = async (ctx, next) => {
    let sayMsg = ctx.request.body.sayMsg || '';
    let userId = ctx.session.userId;
    let say = await Message.create({
        fromUserId: userId,
        content: sayMsg
    });

    let data = JSON.stringify(say);
    console.log(data);
    ctx.body = { code: 200, data, msg: '发表说说成功' };
}

// 吐槽一下调用的方法
let comment_fn = async (ctx, next) => {
    let commentMsg = ctx.request.body.commentMsg || '';
    let msgId = ctx.request.body.msgId || '';
    let fromUserId = ctx.session.userId;

    // 将评论的信息插入数据库
    let comment = await Comment.create({
        fromUserId: fromUserId,
        msgId: msgId,
        content: commentMsg
    });

    // 因为要查找说说的用户信息，所以这里先查询了说说的信息，拿到发表说说的用户的id
    let msg = await Message.findOne({
        where: {
            id: msgId
        }
    });

    let toUserId = msg === undefined ? '0' : msg.fromUserId;

    // 在用户表里查询发表说说的用户的信息和发表评论的用户的信息
    let users = await User.findAll({
        where: {
            id: [fromUserId, toUserId]
        }
    });
    console.log(users);
    // 根据评论者的id，查询到说说的用户信息
    var fromUserInfo = JSON.parse(JSON.stringify(users.filter(user => {
        return user.id === fromUserId;
    })[0]));

    // 根据发表说说的id，查询到评论的用户信息
    var toUserInfo = JSON.parse(JSON.stringify(users.filter(user => {
        return user.id === toUserId;
    })[0]));


    let data = JSON.parse(JSON.stringify(comment));

    // 将说说的用户名称和评论的用户名称挂载到数据信息里面，返回前端
    data.fromUserName = fromUserInfo.username;
    data.toUserName = toUserInfo.username;

    ctx.body = { code: 200, data, msg: '吐槽成功' };
}
//查找问题并打印
let index_fn2 = async (ctx, next) => {
    let msgs = JSON.parse(JSON.stringify(await Message.findAll({
        order: [
            ['id']
        ]
    })));
    console.log(msgs);
    let msgsi = [];
    //把查出来的的id存入数据
    msgs.forEach(item => {
        msgsi.push(item.content);

    });
    console.log(msgsi);

    let obj = {
        msgsi: msgs
    }
    ctx.render('Tellme.html', obj);
}
//工作人员入口
let menu_fn = async (ctx, next) => {
    ctx.render('./menu.html')
}
//退出
let logout_fn2 = async (ctx, next) => {
    ctx.session = null;
    ctx.body = { code: 200, msg: '注销成功' };
}//提交
let aggregate_fn = async (ctx, next) => {
    console.log(12);
    let item = ctx.request.body.time || ""
    console.log(item);
    let Question = await question.create({
        questionAnswer: item
    });

    console.log(Question);
    ctx.body = { code: 200, msg: '导入成功' };
}

let backstage = async (ctx, next) => {
    //总人数
    let peopleCounting = await User.findAndCountAll({
    })
    console.log(peopleCounting);
    let peoC = Number(peopleCounting.count)
    console.log("总人数");
    console.log(peoC);


    //总分
    let totalPoints = await question.findAll({
        attributes: ["questionAnswer"]
    })
    console.log(totalPoints);
    console.log("个体");
    let unitCont = []
    totalPoints.forEach(function (item, index) {
        unitCont.push(item.dataValues.questionAnswer)
        console.log(item.dataValues.questionAnswer);

    })
    console.log(unitCont);

    let Topx = unitCont.reduce(function (x, y) {
        let x1 = Number(x); let y1 = Number(y)
        return x1 + y1
    })
    console.log("总分");
    console.log(Topx);
    //总条数
    let FindC = await question.findAndCountAll({})
    console.log("总条数");
    console.log(FindC.count);
    //平均分
    let average2 = Number(Topx) / Number(FindC.count)
    console.log("平均分");
    console.log(average2);
    let obj = {
        average2,
        Topx,
        peoC
    }

    ctx.render("select.html", obj)
}
module.exports = {
    '/': ['get', auto, login_fn],
    '/index': ['get', auto, index_fn],
    '/logout': ['post', auto, logout_fn],
    '/register': ['get', register_fn],
    '/loginDone': ['post', loginDone_fn],
    '/registerDone': ['post', registerDone_fn],
    '/say': ['post', say_fn],
    '/comment': ['post', comment_fn],
    '/Tellme': ['get', index_fn2],
    '/menu': ['get', menu_fn],
    '/logout2': ['get', logout_fn2],
    '/aggregate': ['post', aggregate_fn],
    '/select': ['get', backstage]
}
//引用查询：https://www.jianshu.com/p/7052d68bbf40